package com.strato.orm.mybatis.v1_0_0.activator;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;

import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.orm.mybatis.v1_0_0.annotation.handler.MybatisMapperAnnotationChangeObserver;
import com.strato.orm.mybatis.v1_0_0.annotation.handler.MybatisMapperAnnotationHandler;
import com.strato.orm.mybatis.v1_0_0.factory.SqlSessionFactoryProvider;
import com.strato.orm.mybatis.v1_0_0.factory.SqlSessionFactoryProviderImpl;

public class Activator implements BundleActivator,BundleListener {

	private static MybatisMapperAnnotationHandler handler;
	private static MybatisMapperAnnotationChangeObserver observer;
	private static SqlSessionFactoryProvider provider;
	private static BundleContext context;
	@Override
	public void start(BundleContext bundleContext) throws Exception {
		context=bundleContext;
		handler=new MybatisMapperAnnotationHandler();
		BundleUtil.exportServices(bundleContext, handler, null, null);
		observer=new MybatisMapperAnnotationChangeObserver();
		Thread t=new Thread(observer);
		t.start();
		provider=new SqlSessionFactoryProviderImpl();
		BundleUtil.exportServices(bundleContext, provider, null, null);
		bundleContext.addBundleListener(this);
	}

	@Override
	public void stop(BundleContext context) throws Exception {
		if(observer!=null){
			observer.stop();
			observer=null;
		}
		handler=null;
		provider=null;
	}

	@Override
	public void bundleChanged(BundleEvent event) {
		if(event.getType()==BundleEvent.UNRESOLVED){
			if(handler!=null){
				handler.clear(event.getBundle().getSymbolicName());
			}
		}
	}

	public static MybatisMapperAnnotationChangeObserver getObserver() {
		return observer;
	}

	public static MybatisMapperAnnotationHandler getHandler() {
		return handler;
	}

	public static SqlSessionFactoryProvider getProvider() {
		return provider;
	}

	public static BundleContext getContext() {
		return context;
	}

}
